/*
 *****************************************************************************
 * Copyright (C) 2005-2014 UC Mobile Limited. All Rights Reserved
 * File			: HUWebViewController.m
 *
 * Description	: HUWebViewController
 *
 * Author		: lizhidong@ucweb.com
 *
 * History		: Creation, 14-12-20, lizhidong@ucweb.com, Create the file
 ******************************************************************************
 **/

#import <Foundation/Foundation.h>

#import "HUWebViewController.h"

@interface HUWebViewController ()<UIWebViewDelegate,UITextFieldDelegate>
{
    
}

@property(nonatomic,retain)UIWebView *webView;
@property(nonatomic,retain)UIBarButtonItem *forwardBtn;
@property(nonatomic,retain)UIBarButtonItem *backBtn;
@property(nonatomic,retain)UIBarButtonItem *cancelBtn;
@property(nonatomic,retain)UIBarButtonItem *refreshBtn;
@property(nonatomic,retain)UIBarButtonItem *moreBtn;
@property(nonatomic,retain)UITextField *urlInput;
@property(nonatomic,retain)UIButton *goBtn;

@property(copy)NSString *currentUrl;
@property(copy)NSString *currentTitle;
@property(nonatomic,retain)NSArray *buttonBarArr;

@end

@implementation HUWebViewController

@synthesize webView = _webView;
@synthesize forwardBtn = _forwardBtn;
@synthesize backBtn = _backBtn;
@synthesize cancelBtn = _cancelBtn;
@synthesize refreshBtn = _refreshBtn;
@synthesize moreBtn = _moreBtn;
@synthesize urlInput = _urlInput;
@synthesize goBtn = _goBtn;
@synthesize currentTitle = _currentTitle;
@synthesize currentUrl = _currentUrl;
@synthesize buttonBarArr = _buttonBarArr;


-(void)deallocs
{
    _webView.delegate = nil;
    _webView = nil;
    
    _urlInput.delegate = nil;
    _urlInput = nil;
    
    [_forwardBtn release];
    _forwardBtn = nil;
    
    [_backBtn release];
    _backBtn = nil;
    
    [_cancelBtn release];
    _cancelBtn = nil;
    
    [_refreshBtn release];
    _refreshBtn = nil;
    
    [_moreBtn release];
    _moreBtn = nil;
    
    [_goBtn release];
    _goBtn = nil;
    
    [_currentUrl release];
    _currentUrl = nil;
    
    [_currentTitle release];
    _currentTitle = nil;
    
    [_buttonBarArr release];
    _buttonBarArr = nil;
    
    [super dealloc];
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self.view setBackgroundColor:[UIColor whiteColor]];
    
    self.navigationItem.hidesBackButton = YES;
    self.navigationController.navigationBarHidden = YES;
    [self.navigationController.navigationBar setFrame:CGRectMake(0, 0,
                                                                self.view.frame.size.width ,
                                                                 30)];

    _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 30,
                                                           self.view.frame.size.width ,
                                                           self.view.frame.size.height - 70)];
    _webView.delegate = self;
    _webView.scalesPageToFit = YES;
    [self.view addSubview:_webView];
    
    _urlInput = [[UITextField alloc] initWithFrame:CGRectMake(0,
                                                              self.navigationController.view.frame.origin.y + 22,
                                                              self.view.frame.size.width - 50,
                                                              self.navigationController.navigationBar.frame.size.height)];
    [_urlInput setBorderStyle:UITextBorderStyleRoundedRect];
    [_urlInput setBackgroundColor:[UIColor whiteColor]];
    [_urlInput setPlaceholder:@"Enter Url Here"];
    _urlInput.delegate = self;
    
    //[self.navigationController.navigationBar addSubview:_urlInput];
    [self.view addSubview:_urlInput];
    
    _goBtn = [[UIButton alloc] initWithFrame:CGRectMake(
                                                self.navigationController.view.frame.origin.x
                                                + _urlInput.frame.size.width,
                                                self.navigationController.view.frame.origin.y + 22 ,50,
                                                self.navigationController.navigationBar.frame.size.height)];
    [_goBtn setTitle:@"Go" forState:UIControlStateNormal];
    [_goBtn setBackgroundColor:[UIColor whiteColor]];
    [_goBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_goBtn setTitleColor:[UIColor blueColor] forState:UIControlStateHighlighted];
    [_goBtn addTarget:self action:@selector(loadUrl:)  forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_goBtn];
    
    _buttonBarArr = [[self buttonBarItems] retain];
    
    UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0,self.view.frame.size.height - 40, self.view.frame.size.width, 40)];
    toolbar.items = _buttonBarArr;
    
    [self.view addSubview:toolbar];
    
    [toolbar release];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

-(void)loadUrl:(id)sender
{
    [_urlInput resignFirstResponder];
    
    [self webViewLoadRequestWithString:_currentUrl];
}

- (NSArray *)buttonBarItems
{
 
    _backBtn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"UIButtonBarArrowLeft@2x.png"]
                                                    style:UIBarButtonItemStyleBordered
                                                    target:self
                                                    action:@selector(backBtnTapped:)];
    _backBtn.tintColor = [UIColor blackColor];
    _backBtn.width = 50.0;
    [_backBtn setEnabled:NO];
    [_backBtn setTag:1];
    
    _forwardBtn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"UIButtonBarArrowRight@2x.png"]
                                                       style:UIBarButtonItemStyleBordered
                                                      target:self
                                                      action:@selector(forwardBtnTapped:)];
    _forwardBtn.tintColor = [UIColor blackColor];
    _forwardBtn.width = 50.0;
    [_forwardBtn setEnabled:NO];
    [_forwardBtn setTag:2];
    
    _cancelBtn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"NavigationBarStopLoading@2x.png"]
                                                                style:UIBarButtonItemStyleBordered
                                                               target:self
                                                               action:@selector(cancelBtnTapped:)];
    _cancelBtn.tintColor = [UIColor blackColor];
    _cancelBtn.width = 50.0;
    [_cancelBtn setEnabled:NO];
    [_cancelBtn setTag:3];
    
    _refreshBtn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"UIButtonBarRefresh@2x.png"]
                                                                  style:UIBarButtonItemStyleBordered
                                                                 target:self
                                                                 action:@selector(refreshBtnTapped:)];
    _refreshBtn.tintColor = [UIColor blackColor];
    _refreshBtn.width = 50.0;
    [_refreshBtn setEnabled:NO];
    [_refreshBtn setTag:4];
    
    _moreBtn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"UIButtonBarBookmarks@2x.png"]
                                                                   style:UIBarButtonItemStyleBordered
                                                                  target:self
                                                                  action:@selector(moreBtnTapped:)];
    _moreBtn.width = 50.0;
    _moreBtn.tintColor = [UIColor blackColor];
    [_moreBtn setTag:5];
    
    UIBarButtonItem *flexItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                                                              target:nil
                                                                              action:nil];
    
    NSArray *array = [NSArray arrayWithObjects: flexItem,_backBtn,_forwardBtn,
                                                _cancelBtn,_refreshBtn,_moreBtn,(id)nil];
    [flexItem release];
    return array;
}

-(void)backBtnTapped:(id)sender
{
    [_webView goBack];
}

-(void)forwardBtnTapped:(id)sender
{
    [_webView goForward];
}

-(void)cancelBtnTapped:(id)sender
{
    [_webView stopLoading];
}

-(void)refreshBtnTapped:(id)sender
{
    [_webView reload];
}

-(void)moreBtnTapped:(id)sender
{
    [_urlInput setHidden:YES];
    [_goBtn setHidden:YES];
    [self.navigationController popViewControllerAnimated:NO];
}


-(void)refreshBtnState
{
    [_refreshBtn setEnabled:YES];
    [_cancelBtn setEnabled:NO];
    
    if([_webView canGoBack])
    {
        [_backBtn setEnabled:YES];
    }
    
    if ([_webView canGoForward])
    {
        [_forwardBtn setEnabled:YES];
    }
}

-(void)webViewLoadRequestWithString:(NSString*)urlString
{
    if (urlString.length != 0 )
    {
        
        if (![urlString hasPrefix:@"http://"]) {
            urlString = [NSString stringWithFormat:@"%@%@",@"http://",urlString];
        }
        
        
        NSURL *url = [NSURL URLWithString:urlString];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        
        _currentUrl = [urlString retain];
        
        _urlInput.text = urlString;
        
        [_webView loadRequest:request];
        
    }
    else
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"出错了！" message:@"URL非法，请重新输入" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
        [alertView show];
        [alertView release];
    }
    

}


#pragma UIWebView delegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    _currentUrl = [request.URL.absoluteString retain];
    
    [_urlInput setText:_currentUrl];
    
    return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    [_refreshBtn setEnabled:NO];
    [_cancelBtn setEnabled:YES];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [self refreshBtnState];
    
    NSString *title = [_webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    NSString *url = [_webView stringByEvaluatingJavaScriptFromString:@"window.location.href"];
    
    _currentTitle = [title retain];
    _currentUrl = [url retain];
    
    [_urlInput setText:_currentTitle];
    
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [self refreshBtnState];
    
    _currentTitle = @"出错了！";
    
    NSLog(@"Fail url: %@",[webView.request URL]);
    
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"出错了！" message:@"网页加载失败，重新检查网络或者尝试刷新" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
    [alertView show];
    [alertView release];
}

#pragma UITextField Delegate

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if (textField == _urlInput && _currentUrl.length != 0)
    {
        //textField.text = _currentUrl;
        _urlInput.text = _currentUrl;
    }
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    NSString *url = textField.text;
    if (textField == _urlInput) {
        
        [textField resignFirstResponder];
        [self webViewLoadRequestWithString:url];
        
        if (_currentTitle.length != 0) {
            textField.text = _currentTitle;
        }

    }
    return YES;
    
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if (textField == _urlInput) {
        
        [textField resignFirstResponder];
        _currentUrl = [textField.text retain];
        textField.text = _currentTitle;
    }
}

@end
